import pymysql as mysql


class Mysql(object):

    def __init__(self,config):
        if config:
            self.__config = config

    def __connect_db(self):
        try:
            return mysql.connect(**self.__config)
        except Exception as e:
            print(e)

    def query_select_db(self,condition):
        con = self.__connect_db()
        if con:
            cur = con.cursor(mysql.cursors.DictCursor)
            try:
                if type(()) == type(condition):
                    cur.execute(condition[0],condition[1])
                else:
                    cur.execute(condition)
                rows = cur.fetchall() #使获得的结果能return 出去
                print(len(rows))
                cur.close()
                con.close()
                assert len(rows) != 0, "错误:数据不存在"  #捕捉正常错误(内容为空）
                return rows
            except Exception as e:
                print(e)
                return None
        else:
            return None


def main():
    # condition = ("select uname,pname,oname from orderproductsinfo,ebuser,eborder where orderproductsinfo.oid=%s",("10001"))
    # condition = ("select uname,group_concat(oname) from ebuser inner join eborder on eborder.uid=ebuser.uid group by uname ")
    # condition = ("select uname,group_concat(oname),group_concat(pname) from ebuser inner join eborder on eborder.uid=ebuser.uid inner join orderproductsinfo on orderproductsinfo.uid=eborder.uid group by uname ")
    # condition = ("select uname,oname from ebuser inner join eborder on eborder.uid=ebuser.uid inner join orderproductsinfo on orderproductsinfo.uid=eborder.uid where ebuser.uid=%s",("10000000001"))
    # condition = ("select uname,oname,pname,uaddress from ebuser inner join eborder on eborder.uid=ebuser.uid inner join orderproductsinfo on orderproductsinfo.uid=eborder.uid inner join uaddress on uaddress.uid=eborder.uid where ebuser.uid=%s",('10000000001'))
    condition = ("select uname,pname,aphone from ebuser inner join eborder on eborder.uid=ebuser.uid inner join orderproductsinfo on orderproductsinfo.uid=eborder.uid inner join uaddress on uaddress.uid=eborder.uid where orderproductsinfo.pname=%s",("百威"))
    config = {
        'host': '127.0.0.1',
        'port': 3306,
        'user': 'root',
        'passwd': '123456',
        'db': 'py03db',
        'charset': 'utf8'
    }

    sql = Mysql(config=config)
    rows = sql.query_select_db(condition)
    if rows:
        print(rows)
    else:
        print('no datas')


if __name__ == '__main__':
    main()

